package com.my.xl.salary.billdemo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.my.xl.salary.billdemo.pojo.SalaryBill;
import com.my.xl.salary.billdemo.pojo.SalaryCode;
import com.my.xl.salary.billdemo.service.DataService;
import com.my.xl.salary.billdemo.service.DingDingService;
import com.my.xl.salary.billdemo.service.ExportService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "/salarybill")
public class DataCtr {
    @Autowired
    private DingDingService dd;
    @Autowired
    private DataService dataService;
    @Autowired
    private ExportService exportService;

    //免登接口
    @RequestMapping("/login")
    public JSONObject login(HttpServletRequest req){
        System.out.println(new Date()+"<==免登========="+req.getRequestURL());
        String data="";
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(),"utf-8"));
            data=reader.readLine();
        } catch (IOException e) {
            System.out.println(e.getMessage()+"<====免登接口 IO流抛出异常");
            e.printStackTrace();
        }
        String access_token=dd.getAccess_token();
        JSONObject json = new JSONObject();
        //免登码
        if(data!=null){
            String code2 = JSON.parseObject(data).getString("code");
            OapiUserGetuserinfoResponse loginInfo = dd.login(access_token, code2);
            if(loginInfo!=null){
                boolean b=dataService.isLogin(loginInfo.getUserid());
                json.put("code",0);
                json.put("isLogin",b);
                json.put("data",loginInfo);
                json.put("msg","请求成功");
            }
        }else{
            json.put("code",1);
            json.put("data","");
            json.put("isLogin",false);
            json.put("msg","传输的参数为空,请求失败");
        }
        System.out.println(JSON.toJSONString(json)+"<=======login免登====="+new Date()+"============"+req.getRequestURL());
        return json;
    }

    //随机验证码
    @RequestMapping("/sendCode")    //参数 :userId
    public void getCode2(HttpServletRequest req){
        System.out.println(new Date()+"<----sendCode,URL========>"+req.getRequestURL());
        String data="";
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(),"utf-8"));
            data=reader.readLine();
        } catch (IOException e) {
            System.out.println(e.getMessage()+"<====随机验证码 IO流报错");
            e.printStackTrace();
        }
        System.out.println(data+"<====getCode2===传输的参数");
        if(data!=null){
            JSONObject config = JSON.parseObject(data);
            String userId = config.getString("userId");
            //获取随机验证码
            Random random = new Random();
            StringBuffer sb = new StringBuffer();
            for(int i = 0; i <= 5; i++) {
                String s = random.nextInt(10) + "";
                sb.append(s);
            }
            System.out.println(JSON.toJSONString(sb.toString())+"<=====生成的6位随机码");
            String s2 = sb.toString();//<======随机验证码
            if (userId!=null&&!userId.equals("undefined")){
                //保存随机验证码
                SalaryCode s = new SalaryCode();
                s.setCode(s2);
                s.setComment(1);
                s.setUserid(userId);
                boolean b=dataService.saveCode(s);
                if(b){
                    System.out.println("保存随机验证码成功!!!!"+userId);
                }else{
                    System.out.println("保存随机验证码成功!!!!"+userId);
                }
                String access_token = dd.getAccess_token();
                //钉钉发送消息
                String content="【工资条】您的验证码为"+s2+"，如非本人操作，请忽略此消息。";
                dd.sendMsg(userId,content,access_token);
            }else{
                System.out.println("传输的userId错误!!!!!"+userId);
            }
        }
        System.out.println(new Date()+"<=====获取随机验证码======"+req.getRequestURL());

    }

    //用户注册     参数:userId,pwd,code(短信验证码)
    @RequestMapping("/register")
    public JSONObject register(HttpServletRequest req){
        System.out.println(new Date()+"<----register----"+req.getRequestURL());
        String data=null;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(),"utf-8"));
            data=reader.readLine();
        } catch (IOException e) {
            System.out.println(e.getMessage()+"<====用户注册消息验证 IO流报错");
            e.printStackTrace();
        }
        System.out.println(data+"<======register==传输的数据参数");
        JSONObject js = new JSONObject();
        if(data!=null){
            JSONObject map = JSON.parseObject(data);
            boolean b = dataService.registerAcccount(map);
            if(b){
                System.out.println("保存数据成功,验证成功,注册账号成功!!!!"+map.getString("userId"));
                js.put("code",0);
                js.put("success",true);
                js.put("msg","注册账号成功!!!!");
            }else{
                System.out.println("保存数据失败,验证失败,注册账号失败!!!!"+map.getString("userId"));
                js.put("code",1);
                js.put("success",false);
                js.put("msg","注册账号失败!!!!");
            }
        }else{
            System.out.println("前端传输的参数为空!!!!");
            js.put("code",1);
            js.put("success",false);
            js.put("msg","注册账号失败!!!!");
        }
        System.out.println(JSON.toJSONString(js)+"<=======register==="+req.getRequestURL());
        return js;
    }

    //用户登录
    @RequestMapping("/userlogin")   // 参数:userId   pwd
    public JSONObject loginApplication(HttpServletRequest req){
        System.out.println(new Date()+"<----loginApplication----"+req.getRequestURL());
        String data=null;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(),"utf-8"));
            data=reader.readLine();
        } catch (IOException e) {
            System.out.println(e.getMessage()+"<====登录工资条报错 IO流报错");
            e.printStackTrace();
        }
        System.out.println(data+"<=====userlogin====前端传输的参数");
        JSONObject js = new JSONObject();
        if(data!=null){
            JSONObject config = JSON.parseObject(data);
            String userId = config.getString("userId");
            String pwd = config.getString("pwd");
            //判断用户登录工资条
            boolean eq=dataService.compareLoginUser(userId,pwd); //true:登录成功   false:登录失败
            if(eq){
                js.put("code",0);
                js.put("isSuccess",eq);
                js.put("msg","登录成功");
            }else{
                js.put("code",1);
                js.put("isSucces",false);
                js.put("msg","登录失败,参数有误");
            }
        }
        System.out.println(JSON.toJSONString(js)+"<==loginApplication=="+new Date()+"==结束时间=="+req.getRequestURL());
        return js;
    }

    //忘记密码  参数:userId,pwd,code(短信验证码)
    @RequestMapping("/update")
    public JSONObject updateLogin(HttpServletRequest req){
        System.out.println(new Date()+"<-updateLogin-开始时间==="+req.getRequestURL());
        String data=null;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(),"utf-8"));
            data=reader.readLine();
        } catch (IOException e) {
            System.out.println(e.getMessage()+"<====用户忘记密码,修改密码 IO流报错");
            e.printStackTrace();
        }
        JSONObject js = new JSONObject();
        if(data!=null){
            JSONObject map = JSON.parseObject(data);
            boolean b = dataService.updatePwd(map);
            if(b){
                System.out.println("修改密码成功!!!"+map.getString("userId"));
                js.put("code",0);
                js.put("msg","修改密码成功!!!!");
            }else{
                System.out.println("修改密码失败!!!!"+map.getString("userId"));
                js.put("code",1);
                js.put("msg","修改密码失败!!!!");
            }
        }else{
            System.out.println("前端传输的参数为空!!!!");
            js.put("code",1);
            js.put("msg","修改密码失败!!!!");
        }
        System.out.println(JSON.toJSONString(js)+"<===updateLogin===="+new Date()+"<<<<<<<结束时间==="+req.getRequestURL());
        return js;
    }

    //移动端查询工资
    @RequestMapping("/check")
    public JSONObject checkSalary(HttpServletRequest req){
        System.out.println(new Date()+"<==用户查询工资=="+req.getRequestURL());
        String data=null;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(),"utf-8"));
            data=reader.readLine();
        } catch (IOException e) {
            System.out.println(e.getMessage()+"<====查询工资 IO流报错");
            e.printStackTrace();
        }
        SimpleDateFormat y = new SimpleDateFormat("YYYY");
        SimpleDateFormat m = new SimpleDateFormat("MM");
        JSONObject js = new JSONObject();
        if(data!=null){
            JSONObject config = JSON.parseObject(data);
            String userId = config.getString("userId");
            Date date_ = config.getDate("date");
            if(date_==null||userId==null){
                System.out.println("传输的参数有空值!!!!");
                js.put("code",1);
                js.put("data","");
                js.put("msg","参数中存在空值,请求失败");
            }else{
                String year = y.format(date_);
                String month = m.format(date_);
                SalaryBill bill= dataService.checkEmpSalary(userId,year,month);
                js.put("code",0);
                js.put("data",bill);
                js.put("msg","请求成功");
            }
        }else{
            js.put("code",1);
            js.put("data","");
            js.put("msg","参数为空,请求失败");
        }
        System.out.println(JSON.toJSONString(js)+"<==用户查询工资=="+new Date()+"==结束时间==="+req.getRequestURL());
        return js;
    }

    //PC端查询工资
    @RequestMapping("/check2")
    public JSONObject checkSalary2(HttpServletRequest req){
        System.out.println(new Date()+"<----PC端查询工资----开始时间----"+req.getRequestURL());
        String data="";
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(),"utf-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                line = new String(line.getBytes(), "utf-8");
                data += line;
            }
        } catch (IOException e) {
            System.out.println(e.getMessage()+"<====查询工资 IO流报错");
            e.printStackTrace();
        }
        SimpleDateFormat y = new SimpleDateFormat("YYYY");
        SimpleDateFormat m = new SimpleDateFormat("MM");
        JSONObject js = new JSONObject();
        if(!data.equals("")){
            JSONObject config = JSON.parseObject(data);
            String userId = config.getString("userId");
            Date startDate = config.getDate("startDate");
            Date endDate = config.getDate("endDate");
            if(userId!=null&&!userId.equals("")&&startDate!=null&&endDate!=null){
                int year1=Integer.parseInt(y.format(startDate));
                int year2=Integer.parseInt(y.format(endDate));
                int st=Integer.parseInt(m.format(startDate));
                int en=Integer.parseInt(m.format(endDate));
                if(year1==year2){
                    //月份列表  未跨年份
                    ArrayList<String> monthArr = getMonthArr(st, en, year1, year2);
                    List<SalaryBill> dataList= dataService.getExportData(monthArr,y.format(endDate),userId);
                    js.put("code",0);
                    js.put("data",dataList);
                    js.put("msg","请求成功");
                }else{
                    System.out.println("日期跨年份!!!");
                    js.put("code",1);
                    js.put("data","");
                    js.put("msg","日期跨年份,请求失败");
                }
            }else{
                System.out.println("传输的参数中有空值!!!!=======PC端查询工资=======");
                js.put("code",1);
                js.put("data","");
                js.put("msg","参数为空,请求失败");
            }
        }else{
            js.put("code",1);
            js.put("data","");
            js.put("msg","参数为空,请求失败");
        }
        System.out.println(JSON.toJSONString(js)+"<==PC端查询工资=="+new Date()+"===结束时间==="+req.getRequestURL());
        return js;
    }

    //excel导出
    @RequestMapping("/exportExcel")
    public JSONObject exportExcel(HttpServletRequest req,HttpServletResponse res){
        System.out.println(new Date()+"<===导出excel表格===开始时间=="+req.getRequestURL());
        String data="";
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(),"utf-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                line = new String(line.getBytes(), "utf-8");
                data += line;
            }
        } catch (IOException e) {
            System.out.println(e.getMessage()+"<====导出excel IO流报错");
            e.printStackTrace();
        }
        SimpleDateFormat m= new SimpleDateFormat("MM");
        SimpleDateFormat y= new SimpleDateFormat("YYYY");
        JSONObject js = new JSONObject();
        if(!data.equals("")){
            //获取参数
            JSONObject c = JSON.parseObject(data);
            String userId = c.getString("userId");
            Date startDate = c.getDate("startDate");
            Date endDate = c.getDate("endDate");
            if(userId==null||userId.equals("")||startDate==null||endDate==null){
                System.out.println("传输的参数为空!!!===exportExcel=====");
                js.put("code",1);
                js.put("data","");
                js.put("msg","导出excel失败");
            }else{
                int st=0;
                int en=0;
                int year=0;
                int year2=0;
                year=Integer.parseInt(y.format(startDate));
                year2=Integer.parseInt(y.format(endDate));
                st=Integer.parseInt(m.format(startDate));
                en=Integer.parseInt(m.format(endDate));
                //月份列表  未跨年份
                ArrayList<String> monthArr = getMonthArr(st, en, year, year2);
                //查询需要导出的数据  解密后的数据
                List<SalaryBill> dataList= dataService.getExportData(monthArr,y.format(endDate),userId);
                ArrayList<Object> titleArr = new ArrayList<>();
                titleArr.add("序号");
                titleArr.add("姓名");
                titleArr.add("基本工资");
                titleArr.add("岗位工资");
                titleArr.add("综合贴");
                titleArr.add("奖金");
                titleArr.add("应发工资");
                titleArr.add("扣社保");
                titleArr.add("扣公积金");
                titleArr.add("扣病事假");
                titleArr.add("税前抵扣");
                titleArr.add("扣个税");
                titleArr.add("实发工资");
                titleArr.add("日期");
                titleArr.add("备注");
                ArrayList<Object> conf = new ArrayList<>();
                conf.add(titleArr);
                for (int i = 0; i < dataList.size(); i++) {
                    SalaryBill obj = dataList.get(i);
                    ArrayList<Object> con = new ArrayList<>();
                    con.add(i+1);
                    con.add(obj.getUsername());
                    con.add(obj.getBasicsalary());
                    con.add( obj.getPostsalary());
                    con.add(obj.getComprohensivesubsidy());
                    con.add(obj.getReward());
                    con.add(obj.getGrosssalary());
                    con.add(obj.getSocialsecurity());
                    con.add(obj.getPubreservefunds());
                    con.add(obj.getLeavesalary());
                    con.add(obj.getPretaxdeduction());
                    con.add(obj.getPersonaltax());
                    con.add(obj.getActualsalary());
                    con.add(obj.getDate2());
                    con.add("");
                    conf.add(con);
                    con=null;
                }
                js.put("code",0);
                js.put("data",conf);
                js.put("msg","导出excel成功");
            }
        }else{
            js.put("code",1);
            js.put("data","");
            js.put("msg","导出excel失败");
        }
        System.out.println(JSON.toJSONString(js)+"<=exportExcel=="+new Date()+"==结束时间===="+req.getRequestURL());
        return js;
    }

    //跨年份未解决
    private ArrayList<String> getMonthArr(int st,int en,int year_st,int year_en){
        ArrayList<String> mArr = new ArrayList<>();
        if(year_st==year_en){
            //未跨年份
            for (int i = 0; i <(en-st+1) ; i++) {
                if(en<10){
                    mArr.add("0"+(st+i));
                }
                if(st>=10){
                    mArr.add((st+i)+"");
                }
                if(st<10&&en>=10){
                    if(st+i<10){
                        mArr.add("0"+(st+i));
                    }else{
                        mArr.add((st+i)+"");
                    }
                }
            }
        }
        return mArr;
    }

    //excel导入
    @RequestMapping("/importExcel")
    public JSONObject importExcel( HttpServletRequest req) throws IOException, ServletException {
        System.out.println(new Date()+"<===导入excel==开始时间,URL====>"+req.getRequestURL());
        Collection<Part> parts = req.getParts();
        System.out.println(JSON.toJSONString(parts)+"<=========================path");
        InputStream inputStream=null;
        String filename=null;
        for (Part d:parts) {
            if (inputStream==null&&filename==null){
                inputStream = d.getInputStream();
                filename = d.getSubmittedFileName();
                break;
            }
        }
        boolean b=false;
        if (inputStream!=null){
            Workbook wb0=null;
            //根据指定的文件输入流导入Excel从而产生Workbook对象
            if (filename.endsWith("xlsx")){
                wb0= new XSSFWorkbook(inputStream);
            }else if (filename.endsWith("xls")){
                wb0 = new HSSFWorkbook(inputStream);
            }
            String access_token = dd.getAccess_token();
            b = exportService.importExecl(wb0,access_token);
            try {

            }catch (Exception e) {
                System.out.println(e.getMessage()+"加密解密数据抛出异常");
                e.printStackTrace();
            }
        }else{
            System.out.println("excel文件传输失败,excel文件为空!!!!!!");
            b=false;
        }
        JSONObject js = new JSONObject();
        if(b){
            js.put("code",0);
            js.put("msg","导入成功");
        }else{
            System.out.println("没有传输的参数!!!!!");
            js.put("code",1);
            js.put("msg","导入失败");
        }
        System.out.println(JSON.toJSONString(js)+"<=importExcel==导入excel文件="+new Date()+"=结束时间=="+req.getRequestURL());
        return js;
    }













}
